-- SPDX-License-Identifier: GPL-3.0-or-later

local extension = Package("ling3")
extension.extensionName = "lingling"

local U = require "packages/utility/utility"

Fk:loadTranslationTable{
  ["lingling__fengeng"] = "分羹",
  [":lingling__fengeng"] = "每轮各限一次，当其他角色使用【桃】或【无中生有】后，你可以将一张牌当同名牌使用。"..
  "<br><br> <font color = '#a40000'>汉祖之神圣，尧以后一人也。",
}

local liuche = General(extension, "lingling__liuche", "han", 4)
--[[local kouluan = fk.CreateTriggerSkill{
  name = "lingling__kouluan",
  anim_type = "special",
  frequency = Skill.Compulsory,
  events = {fk.GameStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cards = U.prepareDeriveCards(room, {
      {"savage_assault", Card.Spade, 7}, --{"savage_assault", Card.Spade, 7},
      {"savage_assault", Card.Club, 7}, --{"savage_assault", Card.Club, 7},
      {"savage_assault", Card.Spade, 13}, {"savage_assault", Card.Spade, 13},
    }, self.name)
    for _, id in ipairs(cards) do
      if room:getCardArea(id) == Card.Void then
        table.removeOne(room.void, id)
        table.insert(room.draw_pile, math.random(1, #room.draw_pile // 2), id)
        room:setCardArea(id, Card.DrawPile, nil)
      end
    end
    room:doBroadcastNotify("UpdateDrawPile", tostring(#room.draw_pile))
  end,
}
local jibei = fk.CreateTriggerSkill{
  name = "lingling__jibei",
  mute = true,
  events = {fk.CardUseFinished, fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then return end
    if event == fk.CardUseFinished then
      return data.card.trueName == "savage_assault" and not target.dead
    elseif event == fk.AfterCardsMove then
      for _, move in ipairs(data) do
        if move.toArea == Card.DiscardPile then
          for _, info in ipairs(move.moveInfo) do
            if Fk:getCardById(info.cardId).trueName == "savage_assault" then
              return true
            end
          end
        end
      end
    end
  end,
  on_trigger = function(self, event, target, player, data)
    if event == fk.CardUseFinished then
      self:doCost(event, target, player, data)
    elseif event == fk.AfterCardsMove then
      local i = 0
      for _, move in ipairs(data) do
        if move.toArea == Card.DiscardPile then
          for _, info in ipairs(move.moveInfo) do
            if Fk:getCardById(info.cardId).trueName == "savage_assault" then
              i = i + 1
            end
          end
        end
      end
      for _ = 1, i do
        if not player:hasSkill(self) then break end
        self:doCost(event, target, player, data)
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    if event == fk.CardUseFinished then
      if player.room:askForSkillInvoke(player, self.name, nil, "#lingling__jibei-damage::"..target.id) then
        self.cost_data = {tos = {target.id}}
        return true
      end
    elseif event == fk.AfterCardsMove then
      self.cost_data = nil
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke(self.name)
    if event == fk.CardUseFinished then
      room:notifySkillInvoked(player, self.name, "offensive")
      room:damage{
        from = player,
        to = target,
        damage = 1,
        skillName = self.name,
      }
    elseif event == fk.AfterCardsMove then
      room:notifySkillInvoked(player, self.name, "drawcard")
      player:drawCards(2, self.name)
    end
  end,
}
liuche:addSkill(kouluan)
liuche:addSkill(jibei)]]--
local sishou = fk.CreateActiveSkill{
  name = "lingling__sishou",
  anim_type = "drawcard",
  card_num = 2,
  target_num = 0,
  prompt = "#lingling__sishou",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = function (self, player, to_select, selected)
    return #selected < 2 and not player:prohibitDiscard(to_select)
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    room:throwCard(effect.cards, self.name, player, player)
    if player.dead then return end
    local ids = {}
    local tag = room:getTag(self.name) or {}
    local dic = {
      ["dismantlement"] = {Card.Spade, 12},
      ["ling__drowning"] = {Card.Spade, 4},
      ["fire_attack"] = {Card.Heart, 3},
      ["duel"] = {Card.Diamond, 1},
    }
    for _, name in ipairs({"dismantlement", "ling__drowning", "fire_attack", "duel"}) do
      local c
      local card = table.filter(tag, function (id)
        return Fk:getCardById(id).name == name and room:getCardArea(id) == Card.Void
      end)
      if #card > 0 then
        c = card[1]
      else
        c = room:printCard(name, dic[name][1], dic[name][2]).id
        table.insert(tag, c)
      end
      table.insert(ids, c)
      room:setCardMark(Fk:getCardById(c), MarkEnum.DestructIntoDiscard, 1)
    end
    room:setTag(self.name, tag)
    room:moveCardTo(ids, Card.PlayerHand, player, fk.ReasonJustMove, self.name, nil, true, player.id, "@@lingling__sishou-inhand")
  end,
}
local sishou_delay = fk.CreateTriggerSkill{
  name = "#lingling__sishou_delay",

  refresh_events = {fk.CardUseFinished},
  can_refresh = function(self, event, target, player, data)
    return target == player and not data.card:isVirtual() and not player.dead and
      table.contains(player.room:getTag("lingling__sishou") or {}, data.card.id)
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    for _, id in ipairs(TargetGroup:getRealTargets(data.tos)) do
      room:addTableMark(player, "lingling__sishou-turn", id)
    end
  end,
}
local sishou_prohibit = fk.CreateProhibitSkill{
  name = "#lingling__sishou_prohibit",
  is_prohibited = function(self, from, to, card)
    return card and #table.filter(from:getTableMark("lingling__sishou-turn"), function (id)
      return id == to.id
    end) > 1
  end,
}
local fengding = fk.CreateTriggerSkill{
  name = "lingling__fengding",
  anim_type = "masochism",
  frequency = Skill.Compulsory,
  events = {fk.Damaged},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self)
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local cards1, cards2 = {}, {}
    room.logic:getEventsByRule(GameEvent.MoveCards, 1, function (e)
      for i = #e.data, 1, -1 do
        local move = e.data[i]
        if move.from and move.moveReason == fk.ReasonDiscard and move.proposer == player.id then
          for j = #move.moveInfo, 1, -1 do
            local info = move.moveInfo[j]
            if (info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip) and
              Fk:getCardById(info.cardId).type ~= Card.TypeBasic then
              if move.from == player.id then
                if #cards1 < 2 and table.contains(room.discard_pile, info.cardId) then
                  table.insertIfNeed(cards1, info.cardId)
                end
              else
                if #cards2 < 2 and table.contains(room.discard_pile, info.cardId) then
                  table.insertIfNeed(cards2, info.cardId)
                end
              end
            end
            if #cards1 > 1 and #cards2 > 1 then
              return true
            end
          end
        end
      end
    end, 1)
    if #cards1 + #cards2 == 0 then return end
    local choice = U.askForChooseCardList(room, player,
      {"lingling__fengding1", "lingling__fengding2"}, {cards1, cards2}, 1, 1, self.name, "#lingling__sishou-ask", false, false)
    local cards = choice[1] == "lingling__fengding1" and cards1 or cards2
    room:moveCardTo(cards, Card.PlayerHand, player, fk.ReasonJustMove, self.name, nil, true, player.id)
  end,
}
sishou:addRelatedSkill(sishou_delay)
sishou:addRelatedSkill(sishou_prohibit)
liuche:addSkill(sishou)
liuche:addSkill(fengding)
Fk:loadTranslationTable{
  ["lingling__liuche"] = "刘彻",
  ["#lingling__liuche"] = "功大威行",
  ["illustrator:lingling__liuche"] = "珊瑚虫",
  ["designer:lingling__liuche"] = "伶",

  --[[["lingling__kouluan"] = "寇乱",
  [":lingling__kouluan"] = "游戏开始时，在牌堆的前面一半额外加入4张【南蛮入侵】。",
  ["lingling__jibei"] = "击北",
  [":lingling__jibei"] = "当一名角色使用【南蛮入侵】结算后，你可以对其造成1点伤害。当一张【南蛮入侵】进入弃牌堆后，你摸两张牌。"..
  "<br><br> <font color = '#a40000'>寇可往，吾亦可往！",
  ["#lingling__jibei-damage"] = "击北：是否对 %dest 造成1点伤害？",
  ["#lingling__jibei-draw"] = "击北：是否摸两张牌？",]]--
  ["lingling__sishou"] = "四狩",
  [":lingling__sishou"] = "出牌阶段限一次，你可以弃置两张牌，获得【过河拆桥】【水淹七军】【火攻】【决斗】各一张，你对同一名角色使用"..
  "“四狩”牌两次后，本回合不能再对其使用牌。",
  ["lingling__fengding"] = "封鼎",
  [":lingling__fengding"] = "当你受到伤害后，你选择获得弃牌堆内最近两张你弃置的：你的非基本牌；其他角色的非基本牌。"..
  "<br><br> <font color = '#a40000'>寇可往，吾亦可往！",
  ["#lingling__sishou"] = "四狩：你可以弃置两张牌，获得【过河拆桥】【水淹七军】【火攻】【决斗】各一张",
  ["@@lingling__sishou-inhand"] = "四狩",
  ["#lingling__sishou-ask"] = "四狩：选择获得的牌",
  ["lingling__fengding1"] = "你弃置的牌",
  ["lingling__fengding2"] = "你弃置其他角色的牌",
}

local xiaohe = General(extension, "lingling__xiaohe", "han", 3)
local jimou = fk.CreateActiveSkill{
  name = "lingling__jimou",
  anim_type = "control",
  prompt = "#lingling__jimou",
  expand_pile = function(self)
    return player:getTableMark(self.name)
  end,
  can_use = function (self, player, card, extra_data)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_num = 1,
  card_filter = function(self, player, to_select, selected)
    if #selected > 0 then return false end
    local mark = player:getTableMark(self.name)
    if table.contains(mark, to_select) then
      local name = Fk:getCardById(to_select).name
      local card = Fk:cloneCard(name)
      card.skillName = self.name
      return card.skill:canUse(player, card)
    end
  end,
  target_filter = function(self, to_select, selected, selected_cards, _, _, player)
    if #selected_cards == 0 then return end
    local card = Fk:cloneCard(Fk:getCardById(selected_cards[1]).name)
    card.skillName = self.name
    if #selected == 0 and to_select == player.id then return end
    return card.skill:targetFilter(to_select, selected, {}, card, {}, player)
  end,
  feasible = function(self, selected, selected_cards, player)
    if #selected_cards == 0 then return end
    local card = Fk:cloneCard(Fk:getCardById(selected_cards[1]).name)
    card.skillName = self.name
    return card.skill:feasible(selected, {}, player, card)
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local card = Fk:cloneCard(Fk:getCardById(effect.cards[1]).name)
    card.skillName = self.name
    room:useCard{
      from = player.id,
      tos = table.map(effect.tos, function(id) return {id} end),
      card = card,
    }
    if target.dead then return end
    if not player.dead then
      local cards = table.filter(player:getTableMark(self.name), function (id)
        local card2 = Fk:getCardById(id)
        return card2.name ~= card.name and card2.skill:canUse(player, card2, {must_targets = {target.id}})
      end)
      if #cards > 0 then
        local dat = U.askForUseRealCard(room, player, cards, nil, self.name, "#lingling__jimou-use::"..target.id,
          {
            expand_pile = cards,
            bypass_times = true,
            must_targets = {target.id},
          }, true, false)
        if dat then
          local use = {
            card = Fk:cloneCard(dat.card.name),
            from = player.id,
            tos = dat.tos,
            extraUse = true,
          }
          use.card.skillName = self.name
          room:useCard(use)
        end
      end
    end
    if target.dead then return end
    room:addPlayerMark(target, "@lingling__jimou", 1)
    local n = 2 - target:getMark("lingling__jimou-tmp")
    room:setPlayerMark(target, "lingling__jimou-tmp", 0)
    if n > 0 then
      local cards = room:getCardsFromPileByRule("nullification", n, "allPiles")
      if #cards > 0 then
        room:moveCardTo(cards, Card.PlayerHand, target, fk.ReasonJustMove, self.name, nil, true, target.id)
      end
    end
  end,

  on_acquire = function (self, player, is_start)
    local room = player.room
    local cards = table.filter(U.getUniversalCards(room, "t"), function(id)
      local card = Fk:getCardById(id)
      return not card.multiple_targets and card.skill:getMinTargetNum() > 0
    end)
    room:setPlayerMark(player, self.name, cards)
  end,
}
local jimou_delay = fk.CreateTriggerSkill{
  name = "#lingling__jimou_delay",

  refresh_events = {fk.CardEffectCancelledOut, fk.TurnStart},
  can_refresh = function(self, event, target, player, data)
    if event == fk.CardEffectCancelledOut then
      return data.to and data.to == player.id and table.contains(data.card.skillNames, "lingling__jimou")
    elseif event == fk.TurnStart then
      return target == player and player:getMark("@lingling__jimou") > 0
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.CardEffectCancelledOut then
      room:addPlayerMark(player, "lingling__jimou-tmp", 1)
    elseif event == fk.TurnStart then
      room:addPlayerMark(player, MarkEnum.MinusMaxCards.."-turn", player:getMark("@lingling__jimou"))
      room:setPlayerMark(player, "@lingling__jimou", 0)
    end
  end,
}
local nadian = fk.CreateTriggerSkill{
  name = "lingling__nadian",
  anim_type = "drawcard",
  events = {fk.AfterCardsMove, fk.CardUsing},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      if event == fk.AfterCardsMove then
        local room = player.room
        local phase_event = room.logic:getCurrentEvent():findParent(GameEvent.Phase)
        if phase_event == nil or phase_event.data[2] ~= Player.Discard then return end
        local cards = {}
        for _, move in ipairs(data) do
          if move.from and move.from ~= player.id and move.moveReason == fk.ReasonDiscard then
            for _, info in ipairs(move.moveInfo) do
              if Fk:getCardById(info.cardId).type == Card.TypeTrick and table.contains(room.discard_pile, info.cardId) then
                table.insertIfNeed(cards, info.cardId)
              end
            end
          end
        end
        cards = U.moveCardsHoldingAreaCheck(room, cards)
        if #cards > 0 then
          self.cost_data = {cards = cards}
          return true
        end
      elseif event == fk.CardUsing then
        return target ~= player and data.card.trueName == "nullification"
      end
    end
  end,
  on_cost = function (self, event, target, player, data)
    if event == fk.AfterCardsMove then
      return player.room:askForSkillInvoke(player, self.name)
    elseif event == fk.CardUsing then
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    if event == fk.AfterCardsMove then
      player.room:moveCardTo(self.cost_data.cards, Card.PlayerHand, player, fk.ReasonJustMove, self.name, nil, true, player.id)
    elseif event == fk.CardUsing then
      player:drawCards(1, self.name)
    end
  end,
}
Fk:loadTranslationTable{
  ["lingling__xiaohe"] = "萧何",
  ["#lingling__xiaohe"] = "开汉首功",
  ["illustrator:lingling__xiaohe"] = "珊瑚虫",
  ["designer:lingling__xiaohe"] = "伶",

  ["lingling__jimou"] = "急谋",
  [":lingling__jimou"] = "出牌阶段限一次，你可以视为对一名其他角色依次使用两张目标为唯一其他角色的牌名不同的普通锦囊牌，结算后其获得X张"..
  "【无懈可击】（X为生效牌数），且其下回合手牌上限-1。",
  ["lingling__nadian"] = "纳典",
  [":lingling__nadian"] = "其他角色于弃牌阶段弃置牌后，你可以获得其中所有锦囊牌。当其他角色使用【无懈可击】时，你摸一张牌。"..
  "<br><br> <font color = '#a40000'>相国人夸佐沛公，收图运饷守关中。<br>不知用蜀为根本，此是兴王第一功。",
  ["#lingling__jimou"] = "急谋：视为对一名角色依次使用两张锦囊，然后其获得生效牌数的【无懈可击】且其下回合手牌上限-1",
  ["#lingling__jimou-use"] = "急谋：再视为对 %dest 使用一张锦囊",
  ["@lingling__jimou"] = "急谋",
}

local huoguang = General(extension, "lingling__huoguang", "han", 4)
local zhuanshan = fk.CreateActiveSkill{
  name = "lingling__zhuanshan",
  anim_type = "control",
  card_num = 0,
  target_num = 1,
  prompt = "#lingling__zhuanshan",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, player, to_select, selected)
    return #selected == 0 and to_select ~= player.id
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    if U.askForPlayCard(room, target, nil, ".|.|.|.|.|trick", self.name, "#lingling__zhuanshan-use:"..player.id) then
      if not player.dead then
        player:drawCards(2, self.name)
      end
    else
      if not table.contains(target.sealedSlots, Player.JudgeSlot) then
        room:addTableMark(player, self.name, target.id)
        room:addPlayerMark(player, MarkEnum.AddMaxCards, 2)
        room:addPlayerMark(target, MarkEnum.AddMaxCards, 2)
        local id = room:getNCards(1)[1]
        local card = Fk:cloneCard("indulgence")
        if Fk:getCardById(id, true).color == Card.Black then
          card = Fk:cloneCard("supply_shortage")
        end
        card:addSubcard(id)
        card.skillName = self.name
        target:addVirtualEquip(card)
        room:moveCardTo(card, Card.PlayerJudge, target, fk.ReasonJustMove, self.name, nil, true)
      end
    end
  end,
}
local zhuanshan_delay = fk.CreateTriggerSkill{
  name = "#lingling__zhuanshan_delay",

  refresh_events = {fk.AfterTurnEnd},
  can_refresh = function (self, event, target, player, data)
    return table.contains(player:getTableMark("lingling__zhuanshan"), target.id)
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local mark = player:getMark("lingling__zhuanshan")
    for i = #mark, 1, -1 do
      if mark[i] == target.id then
        table.remove(mark, i)
      end
    end
    room:setPlayerMark(player, "lingling__zhuanshan", mark)
    room:removePlayerMark(player, MarkEnum.AddMaxCards, 2)
    room:removePlayerMark(target, MarkEnum.AddMaxCards, 2)
  end,
}
local feili = fk.CreateActiveSkill{
  name = "lingling__feili",
  anim_type = "big",
  card_num = 0,
  target_num = 1,
  prompt = "#lingling__feili",
  times = function(self)
    return player.phase == Player.Play and 2 - player:usedSkillTimes(self.name, Player.HistoryGame) or -1
  end,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryGame) < 2 and player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, player, to_select, selected)
    return #selected == 0 and to_select ~= player.id and not table.contains(player:getTableMark(self.name), to_select)
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:addTableMark(player, self.name, target.id)
    room:setPlayerProperty(target, "role_shown", true)
    room:broadcastProperty(target, "role")
    if target.role == "loyalist" and room:getLord() then
      local lord = room:getLord() or room.players[1]
      target.role, lord.role = lord.role, target.role
      room:setPlayerProperty(target, "role_shown", true)
      room:broadcastProperty(target, "role")
      room:setPlayerProperty(lord, "role_shown", true)
      room:broadcastProperty(lord, "role")
      room:changeMaxHp(lord, -1)
      if not target.dead then
        room:changeMaxHp(target, 1)
        if target:isWounded() and not target.dead then
          room:recover{
            who = target,
            num = 1,
            recoverBy = player,
            skillName = self.name,
          }
        end
      end
    end
  end,
}
zhuanshan:addRelatedSkill(zhuanshan_delay)
huoguang:addSkill(zhuanshan)
huoguang:addSkill(feili)
Fk:loadTranslationTable{
  ["lingling__huoguang"] = "霍光",
  ["#lingling__huoguang"] = "摄君如芒",
  ["illustrator:lingling__huoguang"] = "珊瑚虫",
  ["designer:lingling__huoguang"] = "伶",

  ["lingling__zhuanshan"] = "专擅",
  [":lingling__zhuanshan"] = "出牌阶段限一次，你可以令一名其他角色可以使用一张锦囊牌，若其如此做，你摸两张牌；若其未如此做，"..
  "你将牌堆顶的牌置于其判定区，若为红色则视为【乐不思蜀】，若为黑色则视为【兵粮寸断】，然后你与其的手牌上限皆+2，直到其下回合结束。",
  ["lingling__feili"] = "废立",
  [":lingling__feili"] = "每局限两次，出牌阶段限一次，你可以选择一名未以此法选择过的其他角色，其亮出身份牌（若已亮出则跳过），若为忠臣，"..
  "你令主公减1点体力上限并令其与该忠臣交换身份牌，然后新的主公加1点体力上限并回复1点体力。"..
  "<br><br> <font color = '#a40000'>几度咸阳累积尸，尽缘丘冢似焉支。<br>覆车愁杀张车骑，印绶临身必十辞。",
  ["#lingling__zhuanshan"] = "专擅：令一名角色使用一张锦囊牌，若使用则你摸两张牌，若不使用则将延时锦囊置入其判定区",
  ["#lingling__zhuanshan-use"] = "专擅：使用一张锦囊牌，若使用则%src摸两张牌，否则将延时锦囊置入你的判定区",
  ["#lingling__feili"] = "废立：令一名角色亮出身份，若为忠臣，其成为主公！",

  ["$lingling__feili1"] = "今上无德，为天下计，亟需另立新君！",
  ["$lingling__feili2"] = "为国择贤，何惧千古骂名！",
}

local liguang = General(extension, "lingling__liguang", "han", 4)
local shengshi = fk.CreateViewAsSkill{
  name = "lingling__shengshi",
  mute = true,
  prompt = "#lingling__shengshi",
  interaction = function(self)
    local all_names = {"ex_nihilo", "archery_attack"}
    local names = player:getViewAsCardNames(player, self.name, all_names)
    if #names > 0 then
      return UI.CardNameBox {choices = names, all_choices = all_names}
    end
  end,
  card_filter = function(self, player, to_select, selected)
    return #selected < 2
  end,
  view_as = function(self, player, cards)
    if #cards ~= 2 then return end
    local card = Fk:cloneCard(self.interaction.data)
    card.skillName = self.name
    card:addSubcards(cards)
    return card
  end,
  before_use = function (self, player, use)
    local room = player.room
    if use.card.name == "archery_attack" then
      room:notifySkillInvoked(player, self.name, "offensive")
      room:setPlayerMark(player, "lingling__shengshi-phase", "ex_nihilo")
      for _, p in ipairs(room.alive_players) do
        room:handleAddLoseSkills(p, "lingling__shengshi_viewas&", nil, false, true)
      end
    else
      room:notifySkillInvoked(player, self.name, "support")
      room:setPlayerMark(player, "lingling__shengshi-phase", "archery_attack")
    end
  end,
  after_use = function (self, player, use)
    local room = player.room
    if use.card.name == "archery_attack" then
      for _, p in ipairs(room.players) do
        room:handleAddLoseSkills(p, "-lingling__shengshi_viewas&", nil, false, true)
      end
    end
  end,
  enabled_at_play = function (self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,

  attached_skill_name = "lingling__shengshi&",
}
local shengshi_viewas = fk.CreateViewAsSkill{
  name = "lingling__shengshi&",
  mute = true,
  prompt = "#lingling__shengshi&",
  interaction = function(self)
    local all_names = {"ex_nihilo", "archery_attack"}
    local names = player:getViewAsCardNames(player, self.name, all_names)
    if #names > 0 then
      return UI.CardNameBox {choices = names, all_choices = all_names}
    end
  end,
  card_filter = function(self, player, to_select, selected)
    return #selected < 3
  end,
  view_as = function(self, player, cards)
    if #cards ~= 3 then return end
    local card = Fk:cloneCard(self.interaction.data)
    card.skillName = self.name
    card:addSubcards(cards)
    return card
  end,
  before_use = function (self, player, use)
    local room = player.room
    local from = table.find(room.alive_players, function (p)
      return p:hasSkill(shengshi)
    end)
    if from == nil then return "" end
    if use.card.name == "archery_attack" then
      room:notifySkillInvoked(player, self.name, "offensive")
      room:setPlayerMark(from, "lingling__shengshi-phase", "ex_nihilo")
      for _, p in ipairs(room.alive_players) do
        room:handleAddLoseSkills(p, "lingling__shengshi_viewas&", nil, false, true)
      end
    else
      room:notifySkillInvoked(player, self.name, "support")
      room:setPlayerMark(from, "lingling__shengshi-phase", "archery_attack")
    end
  end,
  after_use = function (self, player, use)
    local room = player.room
    if use.card.name == "archery_attack" then
      for _, p in ipairs(room.players) do
        room:handleAddLoseSkills(p, "-lingling__shengshi_viewas&", nil, false, true)
      end
    end
  end,
  enabled_at_play = function (self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
}
local shengshi_delay = fk.CreateTriggerSkill{
  name = "#lingling__shengshi_delay",
  mute = true,
  events = {fk.EventPhaseEnd},
  can_trigger = function(self, event, target, player, data)
    return player:getMark("lingling__shengshi-phase") ~= 0 and not player.dead and
      player:canUse(Fk:cloneCard(player:getMark("lingling__shengshi-phase")))
  end,
  on_cost = function (self, event, target, player, data)
    return player.room:askForSkillInvoke(player, "lingling__shengshi", nil,
      "#lingling__shengshi-invoke:::"..player:getMark("lingling__shengshi-phase"))
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local card = Fk:cloneCard(player:getMark("lingling__shengshi-phase"))
    card.skillName = "shengshi"
    if card.name == "archery_attack" then
      room:notifySkillInvoked(player, "lingling__shengshi", "offensive")
      for _, p in ipairs(room.alive_players) do
        room:handleAddLoseSkills(p, "lingling__shengshi_viewas&", nil, false, true)
      end
    else
      room:notifySkillInvoked(player, "lingling__shengshi", "support")
    end
    room:useCard{
      from = player.id,
      card = card,
    }
    for _, p in ipairs(room.players) do
      room:handleAddLoseSkills(p, "-lingling__shengshi_viewas&", nil, false, true)
    end
  end,
}
local shengshi_vs = fk.CreateViewAsSkill{
  name = "lingling__shengshi_viewas&",
  anim_type = "defensive",
  pattern = "jink",
  prompt = "#lingling__shengshi_viewas&",
  card_filter = function(self, player, to_select, selected)
    return #selected == 0
  end,
  view_as = function(self, player, cards)
    if #cards ~= 1 then return end
    local card = Fk:cloneCard("jink")
    card.skillName = "lingling__shengshi"
    card:addSubcard(cards[1])
    return card
  end,
  enabled_at_response = function (self, player, response)
    return response
  end,
}
local yangsi = fk.CreateTriggerSkill{
  name = "lingling__yangsi",
  anim_type = "defensive",
  events = {fk.EnterDying},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player:usedSkillTimes(self.name, Player.HistoryRound) == 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player, "@@lingling__yangsi", 1)
    room:recover{
      who = player,
      num = 1 - player.hp,
      recoverBy = player,
      skillName = self.name,
    }
  end,

  refresh_events = {fk.TurnStart},
  can_refresh = function (self, event, target, player, data)
    return target == player and player:getMark("@@lingling__yangsi") > 0
  end,
  on_refresh = function (self, event, target, player, data)
    player.room:setPlayerMark(player, "@@lingling__yangsi", 0)
  end,
}
local yangsi_prohibit = fk.CreateProhibitSkill{
  name = "#lingling__yangsi_prohibit",
  is_prohibited = function(self, from, to, card)
    return to:getMark("@@lingling__yangsi") > 0 and card.trueName == "slash"
  end,
}
Fk:addSkill(shengshi_viewas)
Fk:addSkill(shengshi_vs)
shengshi:addRelatedSkill(shengshi_delay)
yangsi:addRelatedSkill(yangsi_prohibit)
liguang:addSkill(shengshi)
liguang:addSkill(yangsi)
Fk:loadTranslationTable{
  ["lingling__liguang"] = "李广",
  ["#lingling__liguang"] = "飞将军",
  ["illustrator:lingling__liguang"] = "漂泊诗人",
  ["designer:lingling__liguang"] = "伶",

  ["lingling__shengshi"] = "声势",
  [":lingling__shengshi"] = "任意角色每个出牌阶段限一次，其可以将三张牌当【无中生有】或【万箭齐发】使用（若为你则改为两张），"..
  "此【万箭齐发】结算时所有角色可以将任意一张牌当【闪】打出；本阶段结束时，你可以视为使用二者中的另一种牌。",
  ["lingling__yangsi"] = "佯死",
  [":lingling__yangsi"] = "每轮限一次，当你进入濒死状态时，你可以回复体力至1点，然后你无法成为【杀】的目标直到你回合开始。"..
  "<br><br> <font color = '#a40000'>桃李不言，下自成蹊。",
  ["#lingling__shengshi"] = "声势：你可以将两张牌当【无中生有】或【万箭齐发】使用，本阶段结束时可以视为使用另一种牌",
  ["lingling__shengshi&"] = "声势",
  [":lingling__shengshi&"] = "出牌阶段限一次，你可以将三张牌当【无中生有】或【万箭齐发】使用，"..
  "此【万箭齐发】结算时所有角色可以将任意一张牌当【闪】打出；本阶段结束时，李广可以视为使用二者中的另一种牌。",
  ["#lingling__shengshi&"] = "声势：你可以将三张牌当【无中生有】或【万箭齐发】使用，本阶段结束时李广可以视为使用另一种牌",
  ["#lingling__shengshi_delay"] = "声势",
  ["#lingling__shengshi-invoke"] = "声势：是否视为使用【%arg】？",
  ["lingling__shengshi_viewas&"] = "声势",
  [":lingling__shengshi_viewas&"] = "你可以将任意一张牌当【闪】打出。",
  ["#lingling__shengshi_viewas&"] = "声势：你可以将任意一张牌当【闪】打出",
  ["@@lingling__yangsi"] = "佯死",
}

return extension
